package com.example.springbootoauth2jwtclientserver.security;

import com.alibaba.fastjson.JSONObject;
import com.example.springbootoauth2jwtclientserver.exception.AjaxResponse;
import com.example.springbootoauth2jwtclientserver.exception.CustomException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        e.printStackTrace();
        Map<String,Object> body = new HashMap<>();
        body.put("timestamp",new Date());
        body.put("status", HttpStatus.FORBIDDEN.value());
        body.put("error",HttpStatus.FORBIDDEN.toString());
        body.put("message",e.getMessage());
        body.put("path",request.getRequestURI());

        AjaxResponse ajaxResponse = AjaxResponse.error(new CustomException(HttpStatus.FORBIDDEN,"抱歉，您没有访问该接口的权限",body));
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        try (PrintWriter writer = response.getWriter()) {
            writer.write(JSONObject.toJSONString(ajaxResponse));
        }
    }
}
